package cc.linker.steplink.crm.task;


import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchant.service.GiftTaskService;
import cc.linker.steplink.crm.merchanth5.pojo.GiveCouponPo;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class GiftTaskTask {

    @Autowired
    private GiftTaskService giftTaskService;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private SmsService smsService;


    public void execute(){
        sendGift();
    }

    @RedisLock("GiftTask_sendGift")
    @Scheduled(cron = "0 59 17 * * ?")
    public void sendGift() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        List<Map<String, Object>> taskList = giftTaskService.getAllTask();
        if (null != taskList && taskList.size() > 0) {
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("%-MM-dd");
            String today = format.format(date);
            for (Map<String, Object> da : taskList) {
                List<Map<String, Object>> birthCustomerList = giftTaskService.getBirthCustomerList(today);
                if(null != birthCustomerList && birthCustomerList.size() > 0){
                    for (Map<String, Object> customer : birthCustomerList) {
                        String customerId = customer.get("customerId").toString();
                        String bindPhone = customer.get("bindPhone").toString();
                        String orgId = customer.get("orgId").toString();

                        Map<String,Object> giftCustomerLog = new HashMap<>();
                        giftCustomerLog.put("customerId",customerId);
                        giftCustomerLog.put("giftTaskId",da.get("id"));
                        giftCustomerLog.put("createYear",year);
                        Integer count = giftTaskService.getSendLogCount(giftCustomerLog);

                        //这个人今年没发过该礼包中的该卡券就发
                        if (!StringUtils.isEmpty(da.get("giftId")) && count == 0) {
                            String[] giftIds = da.get("giftId").toString().split(",");
                            String[] giftContents = giftIds;
                            if (!StringUtils.isEmpty(da.get("giftContent"))) {
                                giftContents = da.get("giftContent").toString().split(",");
                            }
                            CouponCustomerInfo customerInfo = CouponCustomerInfo
                                    .builder()
                                    .customerId(customerId)
                                    .orgId(orgId)
                                    .customerName("")
                                    .customerPhone("")
                                    .cover("")
                                    .sourceUserId("")
                                    .build();
                            int i = 0;
                            List<Object> res = new ArrayList<>();
                            for(String couponId:giftIds){
                                Map<String,Object> giftLog = new HashMap<>();
                                giftLog.put("customerId",customerId);
                                giftLog.put("giftId",couponId);
                                giftLog.put("giftTitle",giftContents[i]);
                                giftLog.put("giftTaskId",da.get("id"));
                                giftLog.put("createYear",year);
                                List<GiveCouponPo> giveCouponPos = new ArrayList<>();
                                GiveCouponPo giveCouponPo = new GiveCouponPo();
                                giveCouponPo.setCouponId(couponId);
                                giveCouponPo.setNum(1);
                                giveCouponPos.add(giveCouponPo);

                                Map<String, Object> param = new HashMap<>();
                                param.put("couponList", giveCouponPos);
                                Object result = this.couponRequest.doRequest("give-coupons", param, customerInfo);
                                List<String> consumptionIds = (List<String>) result;
                                if (consumptionIds != null && consumptionIds.size() == 1) {
                                    giftTaskService.addGiftLog(giftLog);
                                    res.add(consumptionIds.get(0));
                                }
                                i++;
                            }
                            if(res.size()>0){
                                if(!StringUtils.isEmpty(bindPhone) && "1".equals(da.get("ifSms").toString())){
                                    //发短信
//                                    Map<String, Object> nvps = new HashMap<>();
//                                    nvps.put("businessType", "9001");
//                                    nvps.put("mobilNumber", bindPhone);
//                                    nvps.put("params", "{name=" + publicName + "公众号}");
//                                    nvps.put("token", null);
//                                    String result = smsService.sendMsg(orgId, nvps);
//
//                                    Object parse = JSON.parse(result);
//                                    Map ret = (Map) parse;
//                                    if ((Integer) ret.get("rt") != 1) {
//                                        LOGGER.error("生日礼包发送短信通知失败：customerId=>"+customerId+",phone=>"+bindPhone+",ret=>"+JSON.toJSONString(parse));
//                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}
